package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QPD;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.utils.MessageHelper;
import com.herench.bunch.commons.support.RequestMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;


public class DeptClinicInfoConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.LOAD_CURRENT_REMAINING_REGISTRATIONS);
        Element requestElement = document.getRootElement();
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    requestElement.addElement(temp[0]).addText(temp[1]);
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        msa.getErrorCondition().getCe1_Identifier().setValue(doc.getRootElement().elementTextTrim("IsSuccessed"));
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().elementTextTrim("ErrorMsg"));


        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
        Element items = doc.getRootElement().element("Items");

        int index = 0;
        for (Iterator<Element> iterator = items.elementIterator(); iterator.hasNext(); ) {
            Element el = iterator.next();
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
            buffer.append("VisitCode=").append(el.elementTextTrim("VisitCode")).append("#")
                    .append("DeptCode=").append(el.elementTextTrim("DeptCode")).append("#")
                    .append("DoctorCode=").append(el.elementTextTrim("DoctorCode")).append("#")
                    .append("VisitDate=").append(el.elementTextTrim("VisitDate")).append("#")
                    .append("Week=").append(el.elementTextTrim("Week")).append("#")
                    .append("APW=").append(el.elementTextTrim("APW")).append("#")
                    .append("VisitTypeCode=").append(el.elementTextTrim("VisitTypeCode")).append("#")
                    .append("VisitTypeName=").append(el.elementTextTrim("VisitTypeName")).append("#")
                    .append("TotalNumber=").append(el.elementTextTrim("TotalNumber")).append("#")
                    .append("RemainsNumber=").append(el.elementTextTrim("RemainsNumber")).append("#")
                    .append("IsAppoint=").append(el.elementTextTrim("IsAppoint")).append("#")
                    .append("StopType=").append(el.elementTextTrim("StopType")).append("#")
                    .append("AppointType=").append(el.elementTextTrim("AppointType")).append("#")
                    .append("PeriodCode=").append(el.elementTextTrim("PeriodCode")).append("#")
                    .append("InsureFlag=").append(el.elementTextTrim("InsureFlag")).append("#")
                    .append("IsEnabled=").append(el.elementTextTrim("IsEnabled")).append("#")
                    .append("AppStartTime=").append(el.elementTextTrim("AppStartTime")).append("#")
                    .append("AppEndTime=").append(el.elementTextTrim("AppEndTime")).append("#")
                    .append("IsAddReg=").append(el.elementTextTrim("IsAddReg"));
            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }

        return rtbK13;
    }


    @Override
    public Message generatorReqMessage() throws Exception {
        QBP_Q11 qbp = new QBP_Q11();
        qbp.initQuickstart("QBP_Q11", "QBP_Q11", "P");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200030");
        QPD qpd = qbp.getQPD();
        qpd.getMessageQueryName().getIdentifier().setValue("查询患者预约列表（B107）");
        qpd.getQpd2_QueryTag().setValue("QR");
        CE ce = new CE(qbp);
        ce.getCe1_Identifier().setValue("params");
        ce.getCe2_Text().setValue("hisPatientId=0101020K#idCardNo=33108119950702#medCardNo=2018111111#medCardNo=20182222222#startDate=2018-09-06#endDate=2018-09-06");
        qpd.getUserParametersInsuccessivefields().setData(ce);
        System.out.println(MessageHelper.encode(qbp));
        return qbp;
    }
}
